<template>
  <section class="todoapp">
    <hm-header @add-event='handleAdd'></hm-header>
    <hm-main
      :list="showList"
      @delete-event="handleDelete"
      @change-status="changeStatus"
      @change-all-event='handleAll'
    ></hm-main>
    <hm-footer :list='list' @clearall-event='clearAll' :status='status' @status-event='status=$event'></hm-footer>
  </section>
</template>

<script>
const obj = {
  "#/": "all",
  "#/completed": "done",
  "#/active": "undone",
};
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";

export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  data() {
    return {
      // list: [
      //   { id: 1, name: "吃饭", done: false },
      //   { id: 2, name: "睡觉", done: true },

      //   { id: 3, name: "打豆豆", done: false },
      // ],

      // 由于三个组件都要使用这个数据，所以我们利用单向数据流的思想，把数据放在父组件上
      list:JSON.parse(window.localStorage.getItem('list'))||[],
      status:obj[location.hash]||"all",//约定 all代表的全部   done代表的显示已完成  undone未完成
    };
  },
  methods: {
    // 删除通过id找下标
    handleDelete(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    changeStatus(id) {
      const obj = this.list.find((item) => item.id === id);
      obj.done = !obj.done;
    },
    handleAdd(name){
const id=this.list.length==0?1:this.list.slice(-1)[0].id+1
const obj={
  id,
  name,
  done:false,
}
this.list.push(obj)
    },
    handleAll(value){
      this.list.forEach(item=>{item.done=value 
       return item})
    },
    clearAll(){
    this.list=  this.list.filter(item=>item.done===false)
    }

  },
  computed:{
    // showList是筛选后的
    showList(){
      if(this.status==='all'){
        return this.list
      }else if(this.status==='done'){
        return this.list.filter(item=>item.done===true)
      }else{
        return this.list.filter(item=>item.done===false)
        }
    }
  },
  watch:{
    list:{
      handler(newValue){
        window.localStorage.setItem('list',JSON.stringify(newValue))
      }
    }
  }
};
</script>

<style></style>
